package com.qxl.forest.business.controller;

import com.qxl.forest.business.service.MenuService;
import com.qxl.forest.core.annotion.BussinessLog;
import com.qxl.forest.core.annotion.Permission;
import com.qxl.forest.common.constants.Const;
import com.qxl.forest.common.constants.RequestParams;
import com.qxl.forest.business.persistence.dao.MenuDao;
import com.qxl.forest.business.persistence.dao.RelationDao;
import com.qxl.forest.business.persistence.entity.Menu;
import com.qxl.forest.business.persistence.entity.Relation;
import com.qxl.forest.exception.BizExceptionEnum;
import com.qxl.forest.exception.BussinessException;
import com.qxl.forest.util.CommRes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: qiuxinlin
 * @Dercription:
 * @Date: 2017/12/6
 */
@RestController
@RequestMapping("/menu")
public class MenuController extends BaseController {
    @Autowired
    MenuDao menuDao;
    @Autowired
    MenuService menuService;
    @Autowired
    RelationDao relationDao;

    /**
     * 获取所有菜单
     *
     * @return
     */
    @Permission(Const.ADMIN_NAME)
    @PostMapping("/get")
    public CommRes getAll(@RequestBody RequestParams requestParams) {
        if (requestParams.getPageSize() == 0) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        PageRequest pageRequest = new PageRequest(requestParams.getPageNumber(), requestParams.getPageSize());
        Page list = menuDao.findAll(pageRequest);
        return CommRes.success(list);
    }

    /**
     * 新增菜单
     *
     * @param menu
     * @return
     */
    @Permission(Const.ADMIN_NAME)
    @PostMapping("/add")
    @BussinessLog(value = "新增菜单", key = "menu")
    public CommRes add(@RequestBody Menu menu) {
        //判断是否存在该编号
        Menu existedMenu = menuDao.findByCode(menu.getCode());
        if (existedMenu != null) {
            throw new BussinessException(BizExceptionEnum.EXISTED_THE_MENU);
        }
        //设置父级菜单编号
        menuSetPcode(menu);
        menuDao.save(menu);
        return CommRes.successRes();
    }

    /**
     * 删除菜单及其子菜单
     *
     * @param menuId
     * @return
     */
    @Permission(Const.ADMIN_NAME)
    @DeleteMapping("/delete/{menuId}")
    @BussinessLog(value = "获取所有请求的值", key = "menuId")
    public CommRes delete(@PathVariable Integer menuId) {
        menuService.delMenuContainSubMenus(menuId);
        return CommRes.successRes();
    }

    /**
     * 修改菜单
     *
     * @param menu
     * @return
     */
    @Permission(Const.ADMIN_NAME)
    @PutMapping("/update")
    @BussinessLog(value = "修改菜单", key = "menu")
    public CommRes update(@RequestBody Menu menu) {
        //设置父级菜单编号
        menuSetPcode(menu);
        menuDao.save(menu);
        return CommRes.successRes();
    }

    /**
     * 获取菜单树形列表 通过elementUi的tree组件的懒加载实现
     *
     * @param pid
     * @return
     */
    @GetMapping(value = "/selectMenuTreeList/{pid}")
    public CommRes selectMenuTreeList(@PathVariable Integer pid) {
        List menus = menuDao.findByPid(pid);
        return CommRes.success(menus);
    }

    /**
     * 通过角色id查询菜单id，在权限配置的时候默认选中该角色已经有的菜单使用
     *
     * @param roleId
     * @return
     */
    @GetMapping("/getMenusIdByRoleId/{roleId}")
    public CommRes getMenusIdByRoleId(@PathVariable Integer roleId) {
        List<Relation> relations = relationDao.findByRoleid(roleId);
        List menusId = new ArrayList();
        for (Relation relation : relations) {
            menusId.add(relation.getMenuid());
        }
        return CommRes.success(menusId);
    }

    /**
     * 根据请求的父级菜单编号设置pcode和层级
     *
     * @param menu
     */
    private void menuSetPcode(Menu menu) {
        if (StringUtils.isEmpty(menu.getPcode()) || menu.getPcode().equals("0")) {
            menu.setPcode("0");
            menu.setPcodes("[0],");
            menu.setLevels(1);
        } else {
            Menu pMenu = menuDao.findByCode(menu.getPcode());
            Integer pLevels = pMenu.getLevels();
            Integer pId = pMenu.getId();
            menu.setPcode(pMenu.getCode());

            //如果编号和父编号一致会导致无限递归
            if (menu.getCode().equals(menu.getPcode())) {
                throw new BussinessException(BizExceptionEnum.MENU_PCODE_COINCIDENCE);
            }

            menu.setLevels(pLevels + 1);
            menu.setPid(pId);
            menu.setPcodes(pMenu.getPcodes() + "[" + pMenu.getCode() + "],");
        }
    }
}
